﻿using System;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Forms;
using System.Windows.Input;
using System.Windows.Resources;
using Finder.Data;
using Finder.Properties;
using Finder.Utilities.Helpers;
using Finder.Utilities.KeyCapture;
using Microsoft.Office.Interop.Outlook;
using Application = Microsoft.Office.Interop.Outlook.Application;
using ContextMenu = System.Windows.Forms.ContextMenu;
using Exception = System.Exception;
using MenuItem = System.Windows.Forms.MenuItem;
using MessageBox = System.Windows.MessageBox;

namespace Finder.Views
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow
    {
        /// <summary>
        /// Initializes a new instance of the <see cref="MainWindow"/> class.
        /// </summary>
        public MainWindow()
        {
            FinderGuiHelper.PreventMultipleInstances("Finder");
            InitializeComponent();

            this.Closed += this.MainWindowClosed;
            this.Deactivated += this.MainWindowDeactivated;
            this.Loaded += this.MainWindowLoaded;
        }

        /// <summary>
        /// Gets or sets a value indicating whether this <see cref="MainWindow"/> is open.
        /// </summary>
        /// <value><c>true</c> if open; otherwise, <c>false</c>.</value>
        protected bool Open { get; set; }

        /// <summary>
        /// Gets or sets the kh.
        /// </summary>
        /// <value>The KeyboardHook.</value>
        protected KeyboardHook KeyHook { get; set; }

        /// <summary>
        /// Gets or sets the first click.
        /// </summary>
        /// <value>The first click.</value>
        protected DateTime FirstClick { get; set; }

        /// <summary>
        /// Gets or sets the elements on list count.
        /// </summary>
        /// <value>The elements on list count.</value>
        protected int ElementsOnListCount { get; set; }

        /// <summary>
        /// Gets the list colappsed corner radius.
        /// </summary>
        /// <value>The list colappsed.</value>
        protected CornerRadius ListColappsed
        {
            get
            {
                return new CornerRadius(5.2);
            }
        }

        /// <summary>
        /// Gets the list visible corner radius.
        /// </summary>
        /// <value>The list visible.</value>
        protected CornerRadius ListVisible
        {
            get
            {
                return new CornerRadius(5.2, 5.2, 0, 0);
            }
        }

        /// <summary>
        /// Hots the key detected.
        /// </summary>
        /// <param name="hotKeys">The hot keys.</param>
        /// <returns>True or false.</returns>
        private static bool HotKeyDetected(HotKey hotKeys)
        {
            try
            {
                string[] hotKeyAppCfg = Settings.Default.HotKeyCode.Split('|');
                HotKey hotKeyCfg = new HotKey(Convert.ToInt32(hotKeyAppCfg[0]), Convert.ToInt32(hotKeyAppCfg[1]));
                return hotKeys.Equals(hotKeyCfg);
            }
            catch (Exception)
            {
                return false;
            }
        }

        /// <summary>
        /// Finders the window setup.
        /// </summary>
        private void FinderWindowSetup()
        {
            this.FirstClick = DateTime.Now;
            double primaryScreenHeight = SystemParameters.PrimaryScreenHeight;
            this.ElementsOnListCount = (int)Math.Round(Math.Floor(((primaryScreenHeight / 2) - 100) / 60), 0);
            this.SetListVisiblilityOptions(Visibility.Collapsed);

            StreamResourceInfo streamResourceInfo = System.Windows.Application.GetResourceStream(new Uri("pack://application:,,,/Finder;component/search_business_user.ico"));
            if (streamResourceInfo != null)
            {
                Stream iconStream = streamResourceInfo.Stream;
                NotifyIcon notifyIcon = new NotifyIcon
                                            {
                                                Visible = true,
                                                Icon = new System.Drawing.Icon(iconStream)
                                            };

                notifyIcon.DoubleClick += this.NotifyIconDoubleClick;
                MenuItem[] mi = new MenuItem[2];
                mi[0] = new MenuItem(
                    "Close",
                    delegate
                        {
                            this.Close();
                        });

                mi[1] = new MenuItem(
                    "Config",
                    delegate
                        {
                            new Config().ShowDialog();
                        });

                notifyIcon.ContextMenu = new ContextMenu(mi);
            }
        }

        /// <summary>
        /// Sets the list visiblility options.
        /// </summary>
        /// <param name="visibility">The visibility.</param>
        private void SetListVisiblilityOptions(Visibility visibility)
        {
            brd.Visibility = visibility;

            if (visibility == Visibility.Collapsed)
            {
                this.mask.CornerRadius = this.ListColappsed;
                return;
            }

            this.mask.CornerRadius = this.ListVisible;
        }

        /// <summary>
        /// Based on query provided in txtQuery control, this method will lookd for suitable matches.
        /// </summary>
        private void PerformSearch()
        {
            if (LbxResults == null)
            {
                return;
            }

            string query = txtQuery.Text;
            if (!string.IsNullOrEmpty(query) && !string.IsNullOrWhiteSpace(query))
            {
                var p = from q in EmployeesDataAccess.Employees
                        where
                            q.prc_EMail.Contains(query) ||
                            q.prc_Nazwa.Contains(query) ||
                            q.prc_Opis.Contains(query) ||
                            q.prc_Skrot.Contains(query) ||
                            q.prc_Telefon.Contains(query)
                        select new
                                   {
                                       Name = q.prc_Nazwa,
                                       Desc = q.prc_Opis,
                                       Wew = q.prc_Telefon,
                                       Kom = q.prc_TelefonKomorkowy,
                                       Id = q.prc_ID,
                                       Email = q.prc_EMail,
                                       EmailVisibility = FinderGuiHelper.EmailIconVisibility(q.prc_EMail)
                                   };

                if (p.Any())
                {
                    this.SetListVisiblilityOptions(Visibility.Visible);
                    IQueryable queryable;

                    if (p.Count() > this.ElementsOnListCount)
                    {
                        queryable = p.Skip(0).Take(this.ElementsOnListCount - 1);
                        this.OptionsBottom.Visibility = Visibility.Visible;
                    }
                    else
                    {
                        queryable = p.Skip(0).Take(this.ElementsOnListCount);
                        this.OptionsBottom.Visibility = Visibility.Collapsed;
                    }

                    LbxResults.ItemsSource = queryable;
                }
                else
                {
                    this.SetListVisiblilityOptions(Visibility.Collapsed);
                }
            }
            else
            {
                this.SetListVisiblilityOptions(Visibility.Collapsed);
            }
        }

        /// <summary>
        /// Handles the Loaded event of the MainWindow control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.Windows.RoutedEventArgs"/> instance containing the event data.</param>
        private void MainWindowLoaded(object sender, RoutedEventArgs e)
        {
            this.FinderWindowSetup();
            //// KeyHooking.HotKeyIntercepted += this.KeyHookingHotKeyIntercepted;

            this.SimpleHook();
        }

        private void SimpleHook()
        {
            KeyCapTest t = new KeyCapTest();
        }

        /// <summary>
        /// Keys the hooking_ hot key intercepted.
        /// </summary>
        /// <param name="hotKey">The hot key.</param>
        private void KeyHookingHotKeyIntercepted(HotKey hotKey)
        {
            if (HotKeyDetected(hotKey))
            {
                FinderGuiHelper.ShowFinder(this);
            }
        }

        /// <summary>
        /// Handles the Deactivated event of the MainWindow control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        private void MainWindowDeactivated(object sender, EventArgs e)
        {
            FinderGuiHelper.HideFinder(this);
        }

        /// <summary>
        /// Handles the Closed event of the MainWindow control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        private void MainWindowClosed(object sender, EventArgs e)
        {
            this.KeyHook.Dispose();
        }

        /// <summary>
        /// Handles the DoubleClick event of the notifyIcon control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        private void NotifyIconDoubleClick(object sender, EventArgs e)
        {
            FinderGuiHelper.ShowFinder(this);
        }

        /// <summary>
        /// Handles the TextChanged event of the txtQuery control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.Windows.Controls.TextChangedEventArgs"/> instance containing the event data.</param>
        private void TxtQueryTextChanged(object sender, TextChangedEventArgs e)
        {
            this.PerformSearch();
        }

        /// <summary>
        /// Windows the activated.
        /// </summary>
        /// <param name="sender">The sender.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        private void WindowActivated(object sender, EventArgs e)
        {
            FocusHelper.Focus(this.txtQuery);
        }

        /// <summary>
        /// Called when [send email] is executed by the command.
        /// </summary>
        /// <param name="sender">The sender.</param>
        /// <param name="e">The <see cref="System.Windows.Input.ExecutedRoutedEventArgs"/> instance containing the event data.</param>
        private void OnSendEmail(object sender, ExecutedRoutedEventArgs e)
        {
            int personId = (int)e.Parameter;

            string adressForOutlook = Settings.Default.EmailToOutlook
                                          ? EmployeesDataAccess.Employees.Where(x => x.prc_ID == personId).First().prc_EMail
                                          : EmployeesDataAccess.Employees.Where(x => x.prc_ID == personId).First().prc_Nazwa;

            try
            {
                Application objOutlook = new Application();
                MailItem item = (MailItem)objOutlook.CreateItem(OlItemType.olMailItem);
                item.To = adressForOutlook;
                item.Display();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        /// <summary>
        /// Called when [open contact details page].
        /// </summary>
        /// <param name="sender">The sender.</param>
        /// <param name="e">The <see cref="System.Windows.Input.ExecutedRoutedEventArgs"/> instance containing the event data.</param>
        private void OnOpenContactDetailsPage(object sender, ExecutedRoutedEventArgs e)
        {
            string employeeName = EmployeesDataAccess.Employees.Where(x => x.prc_ID == (int)e.Parameter).First().prc_Nazwa;
            Process.Start(new ProcessStartInfo("http://www.instrukcja.kruk-inkaso.com.pl/images/Intranet/png/" + employeeName + ".png"));
        }

        /// <summary>
        /// BTNs the next page mouse left button up.
        /// </summary>
        /// <param name="sender">The sender.</param>
        /// <param name="e">The <see cref="System.Windows.Input.MouseButtonEventArgs"/> instance containing the event data.</param>
        private void BtnNextPageMouseLeftButtonUp(object sender, MouseButtonEventArgs e)
        {
        }
    }
}